import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.Random;

import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;

public class GuiClient extends JFrame {

	private Questionnaire q2;
	private int id;
	private int qID = 0;

	private JTextArea textArea;
	//private JTextArea est;
	private JComboBox est;
	private JTextArea mot;
	private PreviousButton previous;
	private NextButton next;
	private SaveButton save;
	private JCheckBox box;
	private String qFile;
	private JLabel finalL;
	private SummaryButton summary;
	private GenSummaryButton genSummary;

	public JPanel createContentPane() {

		// Create GUI
		JPanel totalGUI = new JPanel();
		JPanel mainPanel = new JPanel();
		// mainPanel.setBackground(Color.GREEN);
		mainPanel.setLayout(new GridBagLayout());
		GridBagConstraints c = new GridBagConstraints();

		// Global Padding
		// c.weightx = 100;
		// c.weighty = 100;
		c.ipadx = 100;
		c.ipady = 1;
		c.insets = new Insets(5, 5, 5, 5);
		c.fill = GridBagConstraints.NONE;

		// Question area
		textArea = new JTextArea();
		textArea.setMargin(new Insets(10, 10, 10, 10));
		textArea.setText("Delphi question, begin to load a question please...");
		textArea.setRows(5);
		textArea.setColumns(50);
		textArea.setEditable(false);
		textArea.setLineWrap(true);
		textArea.setWrapStyleWord(true);
		JScrollPane qScroll = new JScrollPane(textArea);
		c.gridwidth = 4;
		c.gridx = 0;
		c.gridy = 0;
		mainPanel.add(qScroll, c);

		load();
		// SET ID
		setUserID();
		box = new JCheckBox("Finalized", q2.getQuestion(qID).isFinished());
		box.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent arg0) {
				
				if (box.isSelected()) {
					String finEstim = JOptionPane.showInputDialog("Enter final estimate");
					
					//If cancel or sending empty final estim, set box selected false;
					if (finEstim == null || finEstim.equals("")){
						box.setSelected(false);
					}
					else{
					int finalEst = Integer.parseInt(finEstim);
					q2.getQuestion(qID).finalEstimate(finalEst);
					}
				}
				
				q2.getQuestion(qID).setFinished(box.isSelected());
			}

		});
		finalL = new JLabel("Finalized");
		if (q2.getOwner() == id) {
			// Finished label
			c.gridx = 5;
			c.gridy = 0;
			c.gridwidth = 1;
			mainPanel.add(box, c);
		} else {
			c.gridx = 5;
			c.gridy = 0;
			c.gridwidth = 1;
			mainPanel.add(finalL, c);
		}
		
		String[] estOptions = { "1","2","3","4","5","6","7","8","9","10" };
		//est = new JTextArea();
		est = new JComboBox(estOptions);
		mot = new JTextArea();
		
		if (q2.getOwner() != id) {
			// Est label
			c.gridx = 0;
			c.gridy = 1;
			c.gridwidth = 1;
			mainPanel.add(new JLabel("Estimation:"), c);

			// Estimation Area

//			est.setColumns(20);
//			c.gridx = 1;
//			c.gridy = 1;
//			c.gridwidth = 1;
//			mainPanel.add(est, c);
			
			// est2 JComboBox
			c.gridx = 1;
			c.gridy = 1;
			c.gridwidth = 1;
			mainPanel.add(est, c);

			// Motivation label
			c.gridx = 0;
			c.gridy = 2;
			c.gridwidth = 1;
			mainPanel.add(new JLabel("Motivation:"), c);

			// Motivation Area

			mot.setColumns(50);
			mot.setRows(5);
			mot.setMargin(new Insets(10, 10, 10, 10));
			mot.setLineWrap(true);
			mot.setWrapStyleWord(true);
			JScrollPane sp = new JScrollPane(mot);
			c.gridx = 0;
			c.gridy = 3;
			c.gridwidth= 4;
			mainPanel.add(sp, c);
		} else {
			genSummary = new GenSummaryButton(this);
			c.gridx = 5;
			c.gridy = 1;
			mainPanel.add(genSummary, c);
		}

		// Buttons
		previous = new PreviousButton(this);
		c.gridx = 0;
		c.gridy = 4;
		c.gridwidth = 1;
		mainPanel.add(previous, c);

		next = new NextButton(this);
		c.gridx = 1;
		c.gridy = 4;
		mainPanel.add(next, c);

		save = new SaveButton(this);
		c.ipadx = 5;
		c.gridx = 2;
		c.gridy = 4;
		mainPanel.add(save, c);

		summary = new SummaryButton(this);
		c.ipadx = 5;
		c.gridx = 3;
		c.gridy = 4;
		mainPanel.add(summary, c);

		/*
		 * CreateButton create = new CreateButton(this); c.gridx = 3; c.gridy =
		 * 3; mainPanel.add(create, c);
		 */

		totalGUI.add(mainPanel);
		totalGUI.setOpaque(false);

		save.setEnabled(false);
		displayQuestion();
		if (q2.size() == 1) {
			finalQuestion();
		}

		return totalGUI;
	}

	private static void createAndShowGUI(GuiClient demo) {

		JFrame.setDefaultLookAndFeelDecorated(true);

		JFrame frame = new JFrame("Delphi Method");

		frame.setContentPane(demo.createContentPane());

		frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
		frame.pack();
		frame.setVisible(true);
	}

	private static void createStartWindow(final GuiClient gui) {

		JFrame.setDefaultLookAndFeelDecorated(true);

		final JFrame startframe = new JFrame("Delphi Method");

		JPanel guiPanel = new JPanel();
		JPanel mainPanel = new JPanel();
		mainPanel.setLayout(new GridBagLayout());
		GridBagConstraints c = new GridBagConstraints();

		// Global Padding
		// c.weightx = 100;
		// c.weighty = 100;
		c.ipadx = 10;
		c.ipady = 20;
		c.insets = new Insets(5, 5, 5, 5);
		c.fill = GridBagConstraints.NONE;

		CreateButton b1 = new CreateButton(gui);
		c.gridx = 0;
		c.gridy = 0;
		mainPanel.add(b1, c);

		/*
		 * JButton b2 = new JButton("Edit questionnaire"); c.gridx = 1; c.gridy
		 * = 0; mainPanel.add(b2, c); b2.addActionListener(new ActionListener()
		 * {
		 * 
		 * @Override public void actionPerformed(ActionEvent arg0) {
		 * startframe.setVisible(false); createAndShowGUI(gui); } });
		 */

		JButton b3 = new JButton("Answer questions");
		c.gridx = 2;
		c.gridy = 0;
		mainPanel.add(b3, c);

		b3.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent arg0) {
//				startframe.setVisible(false);
				createAndShowGUI(gui);
			}
		});

		guiPanel.add(mainPanel);
		guiPanel.setOpaque(false);

		startframe.setContentPane(guiPanel);

		startframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		startframe.pack();
		startframe.setVisible(true);

	}

	public static void main(String[] args) {
		GuiClient gui = new GuiClient();
		createStartWindow(gui);
		// createAndShowGUI();

	}

	public boolean saveAnswer() {
		if (q2.getOwner() != id) {
			Question q = q2.getQuestion(qID);
			if (q != null) {
				try {
					Answer a = new Answer(est.getSelectedIndex() + 1, mot.getText());
					q.answer(a, id);

				} catch (Exception e) {
					JOptionPane.showMessageDialog(this,
							"Check your input data!");
					return false;
				}

				// save(q);
			} else {
				JOptionPane.showMessageDialog(this, "Nothing to save");
				return false;
			}

		}

		return true;

	}

	public void save(Questionnaire q, String fileName) {
		// save q to file
		FileOutputStream fs;
		ObjectOutputStream out;
		if (fileName == null) {
			fileName = JOptionPane.showInputDialog("Enter file name");
		}
		File f = new File(fileName);

		if (!f.exists()) {
			try {
				f.createNewFile();
			} catch (IOException e) {
				JOptionPane.showMessageDialog(this, "Error, bad file name");
				System.exit(0);
			}
		}

		try {
			fs = new FileOutputStream(f);
			out = new ObjectOutputStream(fs);

			out.writeObject(q);
			out.close();
			fs.close();
			if (fileName == null) {
				JOptionPane
						.showConfirmDialog(this,
								"That was a funny file name. Do you want to hear a joke?");
				initializeJoke();
			}

		} catch (Exception e) {
			JOptionPane.showMessageDialog(this, e.getMessage());
			System.exit(0);
		}

	}

	public void load() {
		FileInputStream fs;
		ObjectInputStream in;
		String fileName = JOptionPane.showInputDialog("Enter questionnaire file name:");
		File f = new File(fileName);

		if (!f.exists()) {
			JOptionPane.showMessageDialog(this,
					"That file hasn't existed since the birth of the universe");
			System.exit(0);
		} else {
			try {
				fs = new FileInputStream(f);
				in = new ObjectInputStream(fs);

				q2 = (Questionnaire) in.readObject();
				qFile = fileName;
			} catch (Exception e) {
				JOptionPane.showMessageDialog(this, e.getMessage());
				System.exit(0);
			}
		}
	}

	public void setUserID() {
		id = Integer.parseInt(JOptionPane.showInputDialog("Enter user ID"));
		if (!q2.isUser(id) && q2.getOwner() != id) {
			JOptionPane.showMessageDialog(this, "You don't exist, maybe you are a ghost.");
			System.exit(0);
		}
	}

	private void displayQuestion() {
		Question q = q2.getQuestion(qID);
		textArea.setText(q.getQuestion());
		Answer a = q.getAnswer(id);

		
		summary.setEnabled(!q.getSummary().equals(""));

		mot.setEditable(!q.isFinished());
//		est.setEditable(!q.isFinished());
		est.setEnabled(!q.isFinished());
		if (q.isFinished() && q2.getOwner() != id) {
			finalL.setText("Finalized");

		} else {
			finalL.setText("");
		}

		if (a != null) {
			mot.setText(a.getMotivation());
			est.setSelectedIndex(a.getEstimation());
//			est.setText(a.getEstimation() + "");
			
		} else {
			mot.setText("");
//			est.setText("");
			est.setSelectedIndex(0);
		}
		
		box.setSelected(q2.getQuestion(qID).isFinished());
		
	}

	public void nextQuestion(NextButton n) {
		if (saveAnswer()) {
			qID++;
			Question q = q2.getQuestion(qID);
			if (q != null) {
				displayQuestion();
			}
			if (qID == q2.size() - 1) {
				finalQuestion();
			}
			if (qID <= q2.size()) {
				previous.setEnabled(true);
			}
		}
	}

	public void previousQuestion() {
		if (saveAnswer()) {
			qID--;
			Question q = q2.getQuestion(qID);
			if (q != null) {
				displayQuestion();
			}
			if (qID == 0) {
				previous.setEnabled(false);
			}
			if (q2.size() >= qID) {
				displayQuestion();
				next.setEnabled(true);
				save.setEnabled(false);
			}
		}
	}

	public void finalQuestion() {
		next.setEnabled(false);
		save.setEnabled(true);
	}

	public void printSummary() {
		if (q2.getQuestion(qID) != null) {
			new SummaryWindow(q2.getQuestion(qID));
		} else {
			JOptionPane.showMessageDialog(this, "Nothing to summarize");
		}
	}

	private void initializeJoke() {
		String[] j = new String[7];
		j[0] = "Yo mama is so fat that she played the part of the iceberg in the film Titanic";
		j[1] = "Chuck Norris's daughter lost her virginity.. he got it back";
		j[2] = "Chuck Norris have been dead for 20 years, Death just doesn't have the courage to tell him";
		j[3] = "The only reason God calls Himself 'God' is because Chuck Norris was already taken";
		j[4] = "The most important thing in life is to be yourself...\n Unless you can be Batman. Always be Batman.";
		j[5] = "How do you make holy water? You boil the hell out of it";
		j[6] = "Chuck Norris doesn't read any books, he stares at them until they give him the information he wants";

		Random r = new Random();
		JOptionPane.showMessageDialog(this, j[r.nextInt(6)]);
	}

	public Questionnaire getQ() {
		return q2;
	}

	public String getFileName() {
		return qFile;
	}

	public void generateSummary(double conv, String convUnit, String outputUnit) {
		for (int i = 0; i < q2.size(); i++) {
			q2.getQuestion(i).genSummary(conv, convUnit, outputUnit);
		}
		save(q2, qFile);
		JOptionPane.showMessageDialog(this, "Generated summary");
		
		if(!summary.isEnabled())
			summary.setEnabled(true);
	}

}
